package com.atlzk.group.order.service.impl;

import com.atlzk.common.utils.SerializeUtils;
import com.atlzk.group.order.dao.OrderDao;
import com.atlzk.group.order.entity.OrderEntity;
import com.atlzk.group.order.feign.TgouFeignService;
import com.atlzk.group.order.utils.NewRedPacket;
import com.atlzk.group.tgou.entity.KanshopEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atlzk.common.utils.PageUtils;
import com.atlzk.common.utils.Query;

import com.atlzk.group.order.dao.KanDao;
import com.atlzk.group.order.entity.KanEntity;
import com.atlzk.group.order.service.KanService;
import redis.clients.jedis.Jedis;


@Service("kanService")
public class KanServiceImpl extends ServiceImpl <KanDao, KanEntity> implements KanService {

    @Autowired
    private OrderDao orderDao;

    @Autowired
    private TgouFeignService tgouFeignService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public PageUtils queryPage(Map <String, Object> params) {
        IPage <KanEntity> page = this.page(
                new Query <KanEntity>().getPage(params),
                new QueryWrapper <KanEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void kan(OrderEntity orderEntity) {
        OrderEntity orderEntity_new = null;
        //连接本地redis
        Jedis jedis = new Jedis("localhost", 6379);
        byte[] bytes = jedis.get(("kanOrder" + orderEntity.getOmsOrderId()).getBytes());
        //判断redis 中是否存在
        if (bytes == null) {
            //redis中不存在  查询最新记录 存入redis
            orderEntity_new = orderDao.selectById(orderEntity.getOmsOrderId());
            byte[] kanOrder_serialize = SerializeUtils.serialize(orderEntity_new);
//            setex有3个参数：第1个是String类型的key，第2个是int类型的过期 秒数 (单位、秒)，第3个是key对应的value。
            jedis.setex(("kanOrder" + orderEntity_new.getOmsOrderId()).getBytes(),100, kanOrder_serialize);

        }else {
            //redis中存在  直接反序列化获取
            orderEntity_new =(OrderEntity) SerializeUtils.deSerialize(bytes);
        }
        System.out.println(orderEntity_new.toString());
        //砍价记录
        KanEntity kanEntity = new KanEntity();
        //1.判断砍价方式
        //指定刀数
        if (orderEntity_new.getSmsKanshopDaoNum() != null && orderEntity_new.getSmsKanshopDaoNum() > 0 && orderEntity_new.getSmsKanshopDaoNum()-orderEntity_new.getOmsKanDaoNum() > 0 ) {
            kanEntity.setUmsUserId(orderEntity_new.getUmsUserId());
            kanEntity.setOmsOrderId(orderEntity_new.getOmsOrderId());
            kanEntity.setOmsKanCreateDate(new Date());
            //每刀砍价金额
            NewRedPacket newRedPacket = new NewRedPacket();
            List <BigDecimal> bigDecimals = newRedPacket.spiltRedPackets(orderEntity_new.getOmsOrderKanMoney().subtract(orderEntity_new.getSmsKanshopMinPrice()), orderEntity_new.getSmsKanshopDaoNum()-orderEntity_new.getOmsKanDaoNum());
            //这一刀的金额
            kanEntity.setOmsKanMoney(bigDecimals.get(0));
            baseMapper.insert(kanEntity);
            //订单修改
            //已砍刀数+1
            orderEntity_new.setOmsKanDaoNum(orderEntity_new.getOmsKanDaoNum() + 1);
            //应付金额-随机扣款金额
            orderEntity_new.setOmsOrderKanMoney(orderEntity_new.getOmsOrderKanMoney().subtract(kanEntity.getOmsKanMoney()));
            //判断是否达到低价
            if (orderEntity_new.getOmsOrderKanMoney().compareTo(orderEntity_new.getSmsKanshopMinPrice()) == 0 && orderEntity_new.getSmsKanshopDaoNum()==orderEntity_new.getOmsKanDaoNum()) {
                orderEntity_new.setOmsOrderStatus(1);//代付款
                System.out.println("砍价成功");
                //删除对应redis信息
                jedis.del(("kanOrder" + orderEntity_new.getOmsOrderId()).getBytes());
            }
            orderDao.updateById(orderEntity_new);


        }
        else {//每刀MAX金额
            //1.查询订单对应砍价商品
            KanshopEntity kanshopEntity = tgouFeignService.ById(orderEntity_new.getSmsKanshopId());
            BigDecimal maxPrice = kanshopEntity.getSmsKanshopDaoMaxPrice();
            //每次生成范围内的钱数
            BigDecimal multiply = BigDecimal.valueOf(new Random().nextInt(100)*0.01).multiply(maxPrice);
            //补全记录信息
            kanEntity.setUmsUserId(orderEntity_new.getUmsUserId());
            kanEntity.setOmsOrderId(orderEntity_new.getOmsOrderId());
            kanEntity.setOmsKanCreateDate(new Date());
            //判断是否为最后一刀
            if (orderEntity_new.getOmsOrderKanMoney().subtract(multiply).compareTo(orderEntity_new.getSmsKanshopMinPrice()) == 1) {
                kanEntity.setOmsKanMoney(multiply);
                orderEntity_new.setOmsOrderKanMoney(orderEntity_new.getOmsOrderKanMoney().subtract(multiply));
            }else{
                //修改该记录应减钱数为  应付金额（未改变） - 低价   最后一刀
                kanEntity.setOmsKanMoney(orderEntity_new.getOmsOrderKanMoney().subtract(orderEntity_new.getSmsKanshopMinPrice()));
                //这时应付的低价  状态修改
                orderEntity_new.setOmsOrderKanMoney(orderEntity_new.getSmsKanshopMinPrice());
                orderEntity_new.setOmsOrderStatus(1);
                //删除对应redis信息
                jedis.del(("kanOrder" + orderEntity_new.getOmsOrderId()).getBytes());
            }
            //添加记录表
            baseMapper.insert(kanEntity);
            //修改订单信息
            orderEntity_new.setOmsKanDaoNum(orderEntity_new.getOmsKanDaoNum() + 1);
            orderDao.updateById(orderEntity_new);
        }
        //将修改后的redis 进行 序列化  并覆盖
        byte[] kanOrder_serialize = SerializeUtils.serialize(orderEntity_new);
        jedis.set(("kanOrder" + orderEntity_new.getOmsOrderId()).getBytes(), kanOrder_serialize);
    }
}